<?php
namespace app\admin\controller;

class Domain extends Base{
    //
    protected function initialize() {
        parent::initialize();
        $this->model = 'Domain';
    }
    //
    protected function _before_index(){
        $thead = [
            'did' => 'DID',
            'xname' => '推广编号',
            'domain' => '推广域名',
            'tdid' => '域名模版',
            'beian' => '备案号码',
            'company' => '公司名称',
            'used' => '使用状态',
            'addtime' =>'创建时间',
        ];
        $this->assign('thead', $thead);
    }
    //
    protected function _filter($map){
        return $map;
    }
    //
    protected function _after_list($list){
        $tdidArr = [];
        foreach($list as $row){
            $tdidArr[] = $row['tdid'];
        }
        $tdArr = model('TplDomain')->where('tdid', 'in', $tdidArr)->column('tname', 'tdid');
        foreach($list as $key => $row){
            $list[$key]['tdid'] = $tdArr[$row['tdid']] ?? '';
            $list[$key]['used'] = $row['used'] == 1 ? '在用' : '未用';
            $list[$key]['addtime'] = date('Y-m-d H:i:s', $row['addtime']);
        }
        return $list;
    }
    //
    protected function _before_add(){
        $tplArr = model('TplDomain')->where('used', '=', 1)->field('tdid,tname')->order('tdid', 'asc')->select()->toArray();
        $this->assign('tplArr', $tplArr);
        $condition = [];
        $condition['used'] = 1;
        $baArr = model('BlockArea')->where(['use_domain'=>1,'used'=>1])->field('baid,area')->select()->toArray();
        $this->assign('baArr', $baArr);
    }
    //
    protected function _before_insert($data){
        $data = $this->_before_save($data);
        $data['addtime'] = time();
        return $data;
    }
    //
    protected function _after_add($data, $id){
        $this->log(['pk' => 'did', 'value' => $id], $data);
    }
    //
    protected function _before_edit(){
        $this->_before_add();
    }
    //
    protected function _filter_edit($list){
        $list['baids'] = unserialize($list['baids']);
        return $list;
    }
    //
    protected function _before_save($data){
        $data['domain'] = str_replace(['http://','https://', '/'], '', trim($data['domain']));
        $data['baids'] = isset($data['baids']) ? serialize($data['baids']) : serialize([]);
        return $data;
    }
    //
    protected function _after_edit($data){
        $this->log(['pk' => 'did', 'value' => $data['did']], $data);
    }
    //
    protected function _filter_del(){
        return [1];
    }
    //
    protected function _after_del($rows){
        $logs = [];
        foreach($rows as $row){
            $logs[] = ['pk' => 'did', 'value' => $row['did'], 'row' => $row];
        }
        $this->logAll($logs);
    }
}